import os
from dotenv import load_dotenv

# 加载环境变量
load_dotenv()


class Config:
    """应用配置类"""
    
    # Flask配置
    SECRET_KEY = os.getenv('SECRET_KEY', 'dev-secret-key-please-change')
    DEBUG = os.getenv('FLASK_DEBUG', 'False').lower() == 'true'
    
    # MongoDB配置
    MONGODB_HOST = os.getenv('MONGODB_HOST', 'localhost')
    MONGODB_PORT = int(os.getenv('MONGODB_PORT', 27017))
    MONGODB_DB = os.getenv('MONGODB_DB', 'iot_platform')
    MONGODB_USERNAME = os.getenv('MONGODB_USERNAME', '')
    MONGODB_PASSWORD = os.getenv('MONGODB_PASSWORD', '')
    
    @property
    def MONGODB_URI(self):
        if self.MONGODB_USERNAME and self.MONGODB_PASSWORD:
            return f"mongodb://{self.MONGODB_USERNAME}:{self.MONGODB_PASSWORD}@{self.MONGODB_HOST}:{self.MONGODB_PORT}/{self.MONGODB_DB}?authSource=admin"
        return f"mongodb://{self.MONGODB_HOST}:{self.MONGODB_PORT}/{self.MONGODB_DB}"
    
    # MQTT配置
    MQTT_BROKER_HOST = os.getenv('MQTT_BROKER_HOST', 'localhost')
    MQTT_BROKER_PORT = int(os.getenv('MQTT_BROKER_PORT', 1883))
    MQTT_USERNAME = os.getenv('MQTT_USERNAME', 'iot_client')
    MQTT_PASSWORD = os.getenv('MQTT_PASSWORD', 'iot_password_2025')
    MQTT_KEEPALIVE = int(os.getenv('MQTT_KEEPALIVE', 60))
    
    # 心跳配置
    HEARTBEAT_INTERVAL = int(os.getenv('HEARTBEAT_INTERVAL', 60))
    HEARTBEAT_TIMEOUT_MULTIPLIER = int(os.getenv('HEARTBEAT_TIMEOUT_MULTIPLIER', 2))
    HEARTBEAT_TIMEOUT_OFFSET = int(os.getenv('HEARTBEAT_TIMEOUT_OFFSET', 30))
    
    @property
    def HEARTBEAT_TIMEOUT(self):
        """计算心跳超时时间"""
        return self.HEARTBEAT_INTERVAL * self.HEARTBEAT_TIMEOUT_MULTIPLIER + self.HEARTBEAT_TIMEOUT_OFFSET
    
    # 服务器配置
    HOST = os.getenv('HOST', '0.0.0.0')
    PORT = int(os.getenv('PORT', 5000))


config = Config()

